package org.zero.concurrency.demo.example.atomic;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.zero.concurrency.demo.annotations.ThreadSafe;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: concurrency-demo
 * @description:
 * @author: 01
 * @create: 2018-10-15 22:39
 **/
@Slf4j
@ThreadSafe
public class AtomicExample5 {

    /**
     * 所指定的字段必须是使用volatile关键字修饰的
     */
    @Getter
    public volatile int count = 100;

    /**
     * 指定原子性地更新AtomicExample5实例里的count字段
     */
    private static final AtomicIntegerFieldUpdater<AtomicExample5> UPDATER =
            AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class, "count");

    public static void main(String[] args) {
        AtomicExample5 example5 = new AtomicExample5();

        // 期望值为100时，更新为120，更新成功返回true，否则返回false
        if (UPDATER.compareAndSet(example5, 100, 120)) {
            log.info("update success 1, {}", example5.getCount());
        }

        // 此时count=120，所以更新失败返回false
        if (UPDATER.compareAndSet(example5, 100, 120)) {
            log.info("update success 2, {}", example5.getCount());
        } else {
            log.info("update failed, {}", example5.getCount());
        }
    }
}
